package pri.abner.practice.thread.synchronize;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description 
 * @author  Abner Chow
 * @date Created in 2018/11/16 17:25
 * @version v4.2.0
 */
public class LockT {

    public static void main(String[] args) {
        //模拟两个旅游团同时订房
        Thread a = new Thread(new Visitor(), "旅游团");
        Thread b = new Thread(new Visitor(), "自由行");
        //线程启动
        a.start();
        b.start();

    }
}

class Hotel {

    static Lock lock = new ReentrantLock();

    static int room = 100;

    public static int getRoom() {
        return room;
    }

    public static void setRoom(int room) {
        Hotel.room = room;
    }

    public void booking() {
        //同步块，提现取钱操作
        lock.lock();
        room = room - 1;
        System.out.println(Thread.currentThread().getName() + "订房后，还剩房间：" + room);
        lock.unlock();
    }

}

class Visitor implements Runnable{

    Hotel hotel = new Hotel();

    @Override
    public void run() {
        for(int i = 0 ; i < 5 ; i++){
            hotel.booking();
            try{
                Thread.sleep(600);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

    }
}
